package org.luxor.webflux.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Mono;

/**
 * WebSocket 之 服务器端消息处理器
 *
 * @author Mr.Yan  @date: 2021/1/5
 */
@Component
public class EchoHandler implements WebSocketHandler {
    private static final Logger log = LoggerFactory.getLogger(EchoHandler.class);

    @Override
    public Mono<Void> handle(final WebSocketSession session) {
        return session.send(
                session.receive()
                        .map(msg -> {
                            log.info("收到消息：" + msg.getPayloadAsText());
                            String result = "ECHO -> " + msg.getPayloadAsText();
                            log.info("响应消息：" + result);
                            return session.textMessage(result);
                        }));
    }

}